package QRCG;

import java.io.IOException;
import java.util.Random;

import javax.mail.MessagingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ForgotPassword
 */
@WebServlet("/ForgotPassword")
public class ForgotPasswordServe extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String mailAddress = request.getParameter("mail_address");
		// {@code response.sendRedirect} loses request attributes, so {@code
		// RequestDispatcher.forward is used}.
		RequestDispatcher rd = request.getRequestDispatcher("ForgotPassword.jsp");

		boolean success = false;
		if (!Mailer.isValidMailAddress(mailAddress)) {
			request.setAttribute("errorMessage", "The provided mail address is invalid!");
		} else if (!isEmailInDatabase(mailAddress)) { //if there is no one registered
														// with that email
			request.setAttribute("errorMessage",
					"The provided mail address cannot be found in database!");
		} else {
			try {
				Mailer.send(Mailer.getFullMailAddress(), mailAddress, "FORGOT PASSWORD MESSAGE",
						createForgotPasswordMessage(mailAddress));
				request.setAttribute("informationMessage",
						"Check your inbox! We have sent you an email.");
				success = true;
			} catch (MessagingException me) {
				request.setAttribute("errorMessage", "Your message could not be sent. " +
															"Please try again later!");
			}
		}
		// If there is an error in the values provided by the user, keep the
		// values as well as showing the error message.
		if (!success) {
			request.setAttribute("mail_address", mailAddress);
		}
		request.setAttribute("mailSuccess", success);
		rd.forward(request, response);
	}

	/**
	 * Creates an email text to send to the forgetful user. First, it tries to
	 * change user's password with the new created password and then, it creates
	 * an email with respect to the success of the update function.
	 * @param from Email address of the user
	 * @return Email text to send.
	 */
	private String createForgotPasswordMessage(String from) {
		String tempPass = Util.getMD5Hash(String.valueOf(new Random().nextInt())).substring(0, 8);
		if (updatePassword(from, tempPass)) {
			String res = "QR Marks The Spot \n";
			res += "Hi, \n" + "Your temporary password is: " + tempPass + "\n";
			res += "Please change your password as soon as possible!" + "\n";
			return res;
		}
		String res = "QR Marks The Spot \n";
		res += "Hi, \n" + "Unfortunately, we have a technical problem. \n";
		res += "Please try again later!" + "\n";
		return res;
	}

	/**
	 * Checks whether the email address is in the database or not.
	 * @param email Email entered by user
	 * @return True, if the email is in the database. False, otherwise.
	 */
	private boolean isEmailInDatabase(String email) {
		DatabaseManager dk = new DatabaseManager();
		try {
			dk.connect();
			return dk.isEmailInDatabase(email);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Database connection failed. \n");
			return false;
		} finally{
			dk.close();
		}
	}

	/**
	 * Updates password of the user.
	 * @param email Email of the user(necessary to find the user in the database)
	 * @param password New password
	 * @return True, if the password changed successfully. False, otherwise.
	 */
	private boolean updatePassword(String email, String password) {
		DatabaseManager dk = new DatabaseManager();
		try {
			dk.connect();
			return dk.updatePasswordByEmail(email, password);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Database connection failed. \n");
			return false;
		} finally {
			dk.close();
		}
	}

}
